package pt.isec.a21210392.a21190220.ludotwist;

import java.util.ArrayList;
import java.util.LinkedList;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Rect;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;

public class BoardView extends View
{
	private static final int houses = 19;
	private double size;
	private double slack;
	private ArrayList<ToDraw> pins;
	private LinkedList<ArrayList<ToDraw>> queue;
	private boolean drawing = false;
	
	public BoardView(GameActivity activity, DisplayMetrics metrics) 
	{
		super(activity);
		this.pins = new ArrayList<ToDraw>();
		this.queue = new LinkedList<ArrayList<ToDraw>>();
		this.size = (double)(metrics.widthPixels-10)/(double)houses;
		this.slack = size*0.2;
	}
	
	@Override
	protected void onDraw(Canvas canvas)
	{
		drawing = true;
		while(!queue.isEmpty())
		{
			Log.d("Na lista:", queue.size()+"");
			ArrayList<ToDraw> toDraw = queue.removeFirst();
			Log.d("Para desenhar:", toDraw.size()+"");
			canvas.drawColor(Color.TRANSPARENT);
			for(ToDraw pin: toDraw)
			{
				Bitmap bitmap = BitmapFactory.decodeResource(getResources(),pin.getImage());
				canvas.drawBitmap(bitmap,null, new Rect((int)(pin.getColumn()*size+slack),(int)(pin.getLine()*size+slack),(int)(pin.getColumn()*size+size-slack),(int)(pin.getLine()*size+size-slack)), null);
			}			
		}
		drawing = false;
	}
	
	public void addPinToDraw(ToDraw pin, final long time)
	{
		pins.add(pin);
		ArrayList<ToDraw> toAdd = new ArrayList<ToDraw>(pins);
		Log.d("Adicionado:", toAdd.size()+"");
		
		try
		{					
			queue.addLast(toAdd);
			if (!drawing)
			{							
				postInvalidate();
			}
			Thread.currentThread().sleep(time);
		}
		catch(Exception e){Log.d("Exception:",e.getMessage().toString());}
	}
	public void removePinToDraw(ToDraw pin)
	{
		pins.remove(pin);
	}
	public void clearDraws()
	{
		pins.clear();
	}
	public void setDraws(ArrayList<ToDraw> pins)
	{
		this.pins = pins;
		ArrayList<ToDraw> toAdd = new ArrayList<ToDraw>(pins);
		queue.addLast(toAdd);
		if (!drawing)
		{							
			postInvalidate();
		}
	}
	public ArrayList<ToDraw> getDraws()
	{
		return pins;
	}
}
